import { createRouter, createWebHashHistory } from 'vue-router';
import { usePortalRouterStore as useRouterStore } from "@/portal/pinia/router";
import { useNProgress } from '@/utils/progress';

const { start, done } = useNProgress();
const routes = [{
  name: 'notfound',
  path: '/:pathMatch(.*)',
  text: '访问地址不存在',
  meta: {
    title: '访问地址不存在',
  },
  component: () => import('@/error/404.vue')
},{
  name: 'portal',
  path: '/portal/:pageId',
  text: '门户',
  meta: {
    title: '门户',
  },
  component: () => import('@/portal/page/index.vue')
}];

const router = createRouter({
  history: createWebHashHistory(import.meta.env.VITE_WEB_PATH || '/'),
  routes
});

let isInitRouter = false;

const initRouter = async() => {
  const routerStore = useRouterStore();
  await routerStore.initRouter(router);
};

const handleKeepAlive = async(to) => {
  if (to.matched.some(item => item.meta.keepAlive)) {
    if (to.matched && to.matched.length > 2) {
      for (let i = 1; i < to.matched.length; i++) {
        const element = to.matched[i - 1];
        if (typeof element.components.default === 'function') {
          await element.components.default();
          await handleKeepAlive(to);
        }
      }
    }
  }
};

router.beforeEach(async(to) => {
  start();
  const routerStore = useRouterStore();
  to.meta.matched = [...to.matched];
  await handleKeepAlive(to);

  if (!isInitRouter) {
    isInitRouter = true;
    await initRouter();
    if (to.path === '/') {
      let route = routerStore.getShowRoute();
      if (route) {
        return { name: route ? route.name : 'notfound' };
      } else {
        return { path: 'notfound' };
      }
    } else {
      await router.push({ path: to.path, query: to.query, params: to.params }).catch(() => {});
    }
  } else {
    if (to.matched.length) {
      return true;
    } else {
      return { name: 'notfound' };
    }
  }
});

router.afterEach(() => {
  done();
});

router.onError(() => {
  done();
});

export default router;
